﻿var _usermange = {
    depts: [],
    selectedDept: null,
    columns: [
        { title: '', field: 'checkbox', checkbox: true },
        { title: '账号', field: 'LoginName',width:'120px' },
        { title: '姓名', field: 'RealName', width: '120px' },
        { title: '备注', field: 'Remark' },
        {
            title: '状态', field: 'State', width: '120px', formatter: function (val) {
                if (val == 1) {
                    return "正常";
                } else {
                    return "禁用";
                }
            }
        },
        {
            title: '', field: 'EDIT',width:'60px' , formatter: function () {
                return "<a href='#'>编辑</a>";
            }
        },
    ],
    init:function(){
        var that=this;
        that.getDepts();
        $("#btnDeleteUser").click(function () {
            that.deleteUser();
        });
        $("#btnSaveUser").click(function () {
            that.editUser();
        });
        $('#userEdit').on('show.bs.modal', function (event) {
            console.log("show.bs.modal", event);
            if (event.relatedTarget) {
                var button = $(event.relatedTarget);
                if (button.attr("id") == "btnAddUser") {
                    that.setEditUser({ID:0});
                }                
            }
        });

        $('#deptEdit').on('show.bs.modal', function (event) {
            console.log("show.bs.modal", event);
            var form = $("#deptEditForm");
            if (event.relatedTarget) {
                var items, button = $(event.relatedTarget);
                items = $.extend(true, [], that.depts);
                items.push({ Name: '全部', ID: 0, ParentID: -1 });
                $(items).each(function () {
                    this['open'] = true;
                });
                if (button.attr("id") == "btnAddDept") {
                    form.find("[name='ParentID']").val(that.selectedDept.id);
                    form.find("[name='Name']").val('');
                    form.find("[name='ID']").val('0');
                } else if (button.attr("id") == "btnModifyDept") {
                    if (that.selectedDept.id == "0") {
                        toastr.warning("请选择部门");
                        return;
                    }
                    form.find("[name='ParentID']").val(that.selectedDept.row.ParentID);
                    form.find("[name='Name']").val(that.selectedDept.row.Name);
                    form.find("[name='ID']").val(that.selectedDept.id);
                }
                form.find("[name='ParentID']").droptree('destroy');
                form.find("[name='ParentID']").droptree({
                    idLabel: "ID",
                    textLabel: "Name",
                    pidLabel: "ParentID",
                    transition: "ztree",
                    items: items
                });
                if (button.attr("id") == "btnModifyDept") {
                    form.find("[name='ParentID']").droptree('removeNode', 'ID', that.selectedDept.id);
                }
            }
        });

        $('#btnSaveDept').click(function () {
            that.editDept();
        });

        $("#btnDeleteDept").click(function () {
            that.deleteDept();
        });
    },
    getDepts: function () {
        var that = this;
        _utility.ajax({
            type: 'get',
            url:  '/api/Dept/GetDepts',
            success: function (res) {
                if (res.errcode == 0 && res.data.length > 0) {
                    that.depts = res.data;
                }
                that.initDept(0);
            }
        });
    },
    initDept: function (selected) {
        var that = this;
        var root = { "id": "0", "text": "全部", "value": 0, pids: '0', complete: true, "isexpand": true, "checkstate": selected == 0 ? 2 : 1, "hasChildren": true, row: { ID: 0, Name: '全部', PID: "0" } };
        function pushChildrenNodes(node, arr) {
            var childrenNodes = [];
            $(arr).each(function () {
                if (this.ParentID == node.value) {
                    node.hasChildren = true;
                    var cNode = { "id": this.ID + "", "text": this.Name, "value": this.ID, pids: node.pids + ',' + node.value, complete: true, "isexpand": false, "checkstate": selected == this.ID ? 2 : 0, "hasChildren": false, row: this };
                    pushChildrenNodes(cNode, arr);
                    childrenNodes.push(cNode);
                }
            });
            if (childrenNodes.length > 0) {
                node["ChildNodes"] = childrenNodes;
            }
        }
        pushChildrenNodes(root, that.depts);
        if (!that.selectedDept) {
            that.selectedDept = root
        }
        $("#tree").wdtreeview({ showcheck: false, data: [root], cbiconpath: '/Scripts/wdTree/css/images/icons/' });
        $("#tree").click(function(){
            var s = $("#tree").getCurrentNode();
            if (s) {
                if (s.id != that.selectedDept.id) {
                    that.selectedDept = s;
                    //that.bttb.query();
                    that.loadUser();
                }
            }
        });
        that.loadUser();
    },
    loadUser:function(){
        var that = this;
        $("#usertable").bootstrapTable('destroy');
        $("#usertable").bootstrapTable({
            url:'/api/users/query',
            columns: that.columns,
            method: "post",
            striped: true,
            pageList: [10, 25, 50],
            pagination: true,
            paginationLoop: true,
            sidePagination:'server',
            showPaginationSwitch: false,
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            authorization:'basic '+$.cookie('token'),
            singleSelect: true,
            queryParams: function (params) {
                return [that.selectedDept.id];
            },
            ajaxSuccess: function (result) {
                return result;
            },
            onClickCell: function (field, value, row, element) {
                if (field == 'EDIT') {
                    that.setEditUser(row);
                    $('#userEdit').modal('show');
                }
            }
        });
    },
    setEditUser: function (row) {
        var that = this;
        var form = $("#userEditForm");
        if (row.ID == 0) {
            $("#userEditLabel").html("新增人员");                 
            form.find("input").val("");
            form.find("[name='ID']").val(0);
            form.find("[name='DeptID']").val(that.selectedDept.id);
            form.find("[id='deptName']").html(that.selectedDept.text);
            form.find("[name='Remark']").val('');
            form.find("[name='LoginName']").removeAttr('readonly');
        } else {
            $("#userEditLabel").html("编辑人员");
            form.find("[name='ID']").val(row.ID);
            form.find("[name='DeptID']").val(row.DeptID);
            form.find("[name='LoginName']").val(row.LoginName);
            form.find("[name='Password']").val(row.Password);
            form.find("[name='RealName']").val(row.RealName);
            form.find("[name='State']").val(row.State);
            form.find("[id='deptName']").html(that.selectedDept.text);
            form.find("[name='Remark']").val(row.Remark);
            form.find("[name='LoginName']").attr('readonly','readonly')
        }
    },
    deleteUser: function () {
        var that = this;
        var rows = $("#usertable").bootstrapTable("getAllSelections");
        if (rows.length <= 0) {
            toastr.warning("请选择人员");
        } else {
            _utility.ajax({
                url: '/api/users/del?id=' + rows[0].ID,
                type: 'get',
                success: function (res) {
                    if (res.errcode != 0) {
                        toastr.warning(res.errmsg);
                    } else {
                        toastr.info(res.errmsg);
                        that.loadUser();
                    }
                }
            });
        }
    },
    editUser: function () {
        var that = this;
        var form = $("#userEditForm");
        
        var data = {
            ID: $.trim(form.find("[name='ID']").val()),
            LoginName: $.trim(form.find("[name='LoginName']").val()),
            DeptID: $.trim(form.find("[name='DeptID']").val()),
            Password: $.trim(form.find("[name='Password']").val()),
            RealName: $.trim(form.find("[name='RealName']").val()),
            State: $.trim(form.find("[name='State']").val()),
            Remark: $.trim(form.find("[name='Remark']").val()),
        };
        if (data.LoginName == '') {
            toastr.warning('账号不能为空');
            return;
        }
        if (data.Password == '') {
            toastr.warning('密码不能为空');
            return;
        }
        if (data.RealName == '') {
            toastr.warning('姓名不能为空');
            return;
        }
        $("#btnSaveUser").button('loading')
        _utility.postJson({
            url: '/api/users/edit',
            data:JSON.stringify(data),
            success: function (res) {
                $("#btnSaveUser").button('reset');
                if (res.errcode != 0) {
                    toastr.warning(res.errmsg);
                } else {
                    toastr.info(res.errmsg);                    
                    $('#userEdit').modal('hide');
                    that.loadUser();
                }
            }
        });
    },
    deleteDept: function () {
        var that = this;
        var id = that.selectedDept.id;
        if (id <= 0) {
            toastr.warning("请选择部门");
            return;
        } else {
            _utility.ajax({
                url: '/api/dept/delete?id=' + id,
                type: 'get',
                success: function (res) {
                    if (res.errcode != 0) {
                        toastr.warning(res.errmsg);
                    } else {
                        toastr.info(res.errmsg);
                        that.getDepts();
                    }
                }
            });
        }
    },
    editDept: function () {
        var that = this;        
        var form = $("#deptEditForm");
        var data = {
            ID: $.trim(form.find("[name='ID']").val()),
            Name: $.trim(form.find("[name='Name']").val()),
            ParentID: $.trim(form.find("[name='ParentID']").val()),
        };
        if (data.Name == '') {
            toastr.warning('部门名称不能为空');
            return;
        }
        $("#btnSaveDept").button('loading')
        _utility.postJson({
            url: '/api/dept/edit',
            data: JSON.stringify(data),
            success: function (res) {
                if (res.errcode != 0) {
                    toastr.warning(res.errmsg);
                } else {
                    toastr.info(res.errmsg);                    
                    $('#deptEdit').modal('hide');
                    that.getDepts();
                }
                $("#btnSaveDept").button('reset');
            }
        });
    },
};